import type { ApiResponse, ChatSessionResponse, PrivateMessage} from "@/types";
import { get, post, put, del } from "@/utils/request";

/**
 * 创建会话
 * @param targetId 目标用户或群组ID
 * @param type 会话类型（0:私聊 1:群聊）
 * @param lastMessage 最后一条消息
 * @returns Promise<ApiResponse<ChatSessionResponse>> 返回一个Promise，成功时data为会话信息
 */
export const createSession = async (
  targetId: string,
  type: number,
  lastMessage: string | null
): Promise<ApiResponse<ChatSessionResponse>> => {
  return post("/chat/sessions", { targetId, type, lastMessage });
};

/**
 * 根据目标ID获取会话
 * @param targetId 目标ID
 * @returns Promise<ApiResponse<ChatSessionResponse>> 返回一个Promise，成功时data为会话信息
 */
export const getSessionByTargetId = async (
  targetId: string
): Promise<ApiResponse<ChatSessionResponse>> => {
  return get(`/chat/sessions/${targetId}`);
}


/**
 * 获取会话列表
 * @returns Promise<ApiResponse<ChatSessionResponse[]>> 返回一个Promise，成功时data为会话列表
 */
export const getSessionList = async (): Promise<
  ApiResponse<ChatSessionResponse[]>
> => {
  return get("/chat/sessions");
};

/**
 * 设置会话置顶状态
 * @param sessionId 会话ID
 * @param isTop 是否置顶
 * @returns Promise<ApiResponse<void>> 返回一个Promise，成功时data为void
 */
export const setSessionTop = async (
  sessionId: string,
  isTop: boolean
): Promise<ApiResponse<void>> => {
  return put(`/chat/sessions/${sessionId}/top`, { isTop });
};

/**
 * 删除会话
 * @param sessionId 会话ID
 * @returns Promise<ApiResponse<void>> 返回一个Promise，成功时data为void
 */
export const deleteSession = async (
  sessionId: string
): Promise<ApiResponse<void>> => {
  return del(`/chat/sessions/${sessionId}`);
};

/**
 * 清空会话未读消息数
 * @param sessionId 会话ID
 * @returns Promise<ApiResponse<void>> 返回一个Promise，成功时data为void
 */
export const clearUnreadCount = async (
  sessionId: string
): Promise<ApiResponse<void>> => {
  return put(`/chat/sessions/${sessionId}/read`);
};

/**
 * 获取会话历史消息
 * @param sessionId 会话ID
 * @param before 消息ID，获取此消息之前的消息，不传则从最新消息开始
 * @param limit 获取消息数量，默认20条
 * @returns Promise<ApiResponse<Message[]>> 返回一个Promise，成功时data为消息列表
 */
export const getHistoryMessages = async (
  sessionId: string,
  before?: string,
  limit: number = 20
): Promise<ApiResponse<PrivateMessage[]>> => {
  const params = new URLSearchParams();
  if (before) {
    params.append("before", before);
  }
  params.append("limit", limit.toString());
  return get(`/chat/sessions/${sessionId}/messages?${params.toString()}`);
};

/**
 * 清空会话历史消息
 * @param sessionId 会话ID
 * @returns Promise<ApiResponse<void>> 返回一个Promise，成功时data为void
 */
export const clearHistoryMessages = async (
  sessionId: string
): Promise<ApiResponse<void>> => {
  return del(`/chat/sessions/${sessionId}/messages`);
};
